﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Text;

namespace Job.Core
{
    public enum UploadFileResult
    {
        /// <summary>
        /// 上传成功
        /// </summary>
        Success = 0,

        /// <summary>
        /// 文件大小错误（超过限制）
        /// </summary>
        FileSizeError = 1,

        /// <summary>
        /// 扩展名错误
        /// </summary>
        ExtensionNameError = 2,

        /// <summary>
        /// 文件类型错误
        /// </summary>
        FileTypeError = 3,
    }

    /// <summary>
    /// UploadFileHelper 的摘要说明
    /// </summary>
    public class UploadFileHelper
    {
        private int maxFileSize = 2048;
        private string extName = "jpg,gif,jpeg";
        private string fileType = "text/plain,application/pdf,application/octet-stream";
        private FileUpload fileUpload;

        public UploadFileHelper(FileUpload fileUpload)
        {
            this.fileUpload = fileUpload;
        }

        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="saveFilePath">路径</param>
        /// <param name="saveFileName">文件名</param>
        /// <returns></returns>
        public UploadFileResult SaveAs(string saveFilePath, string saveFileName)
        {
            return SaveFile(saveFilePath + saveFileName);
        }

        /// <summary>
        /// 保存文件 自动命名
        /// </summary>
        /// <param name="saveFilePath">路径</param>
        /// <param name="saveFileName">系统返回文件名</param>
        /// <returns></returns>
        public UploadFileResult Save(string saveFilePath, out string saveFileName)
        {
            string _extName = Path.GetExtension(fileUpload.PostedFile.FileName.ToLower());
            saveFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + _extName;
            return SaveFile(saveFilePath + saveFileName);
        }

        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="saveFileName">保存文件路径名称</param>
        /// <returns></returns>
        private UploadFileResult SaveFile(string saveFileName)
        {
            //检测文件扩展名
            if (extName != string.Empty)
            {
                string curFileExt = Path.GetExtension(fileUpload.PostedFile.FileName.ToLower());
                string allowExt = string.Concat(",", extName, ",");
                if (allowExt.IndexOf(string.Concat(",", curFileExt, ",")) == -1)
                    return UploadFileResult.ExtensionNameError;
            }

            //检测文件大小
            if (maxFileSize != 0)
            {
                if (fileUpload.PostedFile.ContentLength > maxFileSize)
                    return UploadFileResult.FileSizeError;
            }

            //检测文件类型
            if (fileType != string.Empty)
            {
                string allowFileType = string.Concat(",", fileType, ",");
                if (allowFileType.IndexOf(fileUpload.PostedFile.ContentType.ToLower()) == -1)
                    return UploadFileResult.FileTypeError;
            }

            //保存文件
            fileUpload.SaveAs(saveFileName);
            return UploadFileResult.Success;
        }


        /// <summary>
        /// 生成水印
        /// </summary>
        /// <param name="filePath"> /aaa/123.gif </param>
        /// <param name="maxWidth">84</param>
        /// <param name="maxHeight">64</param>
        /// <returns></returns>
        public static string GetThumbImage(string filePath, int maxWidth, int maxHeight)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                return string.Empty;
            }
            int startIndex = filePath.LastIndexOf('/');
            string str = filePath.Remove(startIndex);
            FileInfo info = new FileInfo(HttpContext.Current.Server.MapPath(filePath));
            string name = info.Name;
            string directoryName = info.DirectoryName;
            string path = string.Format("{0}/{1}-{2}/{3}", new object[] { directoryName, maxWidth, maxHeight, name });
            if (File.Exists(path))
            {
                FileInfo info2 = new FileInfo(path);
                return string.Format("{0}/{1}-{2}/{3}", new object[] { str, maxWidth, maxHeight, name });
            }
            try
            {
                string str5 = string.Format(@"{0}\{1}-{2}", directoryName, maxWidth, maxHeight);
                System.Drawing.Image image = System.Drawing.Image.FromFile(info.FullName);
                ImageFormat imageFormat = GetImageFormat(info.Extension.Remove(0, 1));
                if (!Directory.Exists(str5))
                {
                    Directory.CreateDirectory(str5);
                }
                if ((maxHeight <= image.Height) || (maxWidth <= image.Width))
                {
                    float num4 = ((float)maxHeight) / ((float)image.Height);
                    float num5 = ((float)maxWidth) / ((float)image.Width);
                    if (num4 > 1f)
                    {
                        num4 = 1f;
                    }
                    if (num5 > 1f)
                    {
                        num5 = 1f;
                    }
                    float num6 = (num5 < num4) ? num5 : num4;
                    int num2 = (int)(image.Width * num6);
                    int num3 = (int)(image.Height * num6);
                    image = image.GetThumbnailImage((int)(image.Width * num6), (int)(image.Height * num6), null, IntPtr.Zero);
                }
                image.Save(string.Format(@"{0}\{1}", str5, name), imageFormat);
                return string.Format("{0}/{1}-{2}/{3}", new object[] { str, maxWidth, maxHeight, name });
            }
            catch
            {
                return string.Empty;
            }
        }

        private static ImageFormat GetImageFormat(string ext)
        {
            switch (ext.ToUpper())
            {
                case "GIF":
                    return ImageFormat.Gif;

                case "JPEG":
                case "JPG":
                    return ImageFormat.Jpeg;

                case "BMP":
                    return ImageFormat.Bmp;

                case "PNG":
                    return ImageFormat.Png;

                case "ICO":
                    return ImageFormat.Icon;
            }
            throw new Exception("无效的图片格式！");
        }

        /// <summary>
        /// 上传最大限制
        /// </summary>
        public int MaxFileSize
        {
            get { return maxFileSize; }
            set { maxFileSize = value; }
        }

        /// <summary>
        /// 允许扩展名   a,b,c
        /// </summary>
        public string ExtensionName
        {
            get { return extName; }
            set { extName = value; }
        }
        /// <summary>
        /// 文件类型    a,b,c
        /// </summary>
        public string FileType
        {
            get { return fileType; }
            set { fileType = value; }
        }
    }

}